package controllers

import (
	"strconv"
	"supershare/backend/models"
	"time"

	"supershare/backend/middleware"

	"github.com/beego/beego/v2/server/web"
)

// GroupBuyStatisticsController 团购统计控制器
type GroupBuyStatisticsController struct {
	web.Controller
}

// GetStatistics 获取团购统计数据
func (c *GroupBuyStatisticsController) GetStatistics() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取时间范围参数
	timeRange := c.GetString("timeRange", "week")
	var startTime, endTime time.Time
	now := time.Now()

	switch timeRange {
	case "week":
		startTime = now.AddDate(0, 0, -7)
	case "month":
		startTime = now.AddDate(0, -1, 0)
	case "year":
		startTime = now.AddDate(-1, 0, 0)
	default:
		startTime = now.AddDate(0, 0, -7)
	}
	endTime = now

	// 获取活动ID参数
	activityId, _ := strconv.ParseInt(c.GetString("activityId"), 10, 64)

	// 如果是加盟商管理员，需要验证活动是否属于该加盟商
	if admin.FranchiseId > 0 && activityId > 0 {
		activity, err := models.GetGroupBuyActivityById(activityId)
		if err != nil || activity == nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "活动不存在",
			}
			c.ServeJSON()
			return
		}

		if activity.FranchiseId != admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权查看该活动统计数据",
			}
			c.ServeJSON()
			return
		}
	}

	// 获取统计数据
	stats, err := models.GetGroupBuyStatistics(startTime.Unix(), endTime.Unix(), activityId, admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取统计数据失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data":    stats,
	}
	c.ServeJSON()
}
